const express = require('express'); //引入express模块
const app = express();//实例化express
const port = 5001;//端口号
const sha1 = require('sha1');//引入sha1加密模块

const {
    getUserSendPostAsync,
    xmlToJsFunc,
} = require('./pageage/getUserSendAsync');//获取公众号用户发送的数据

const {appID,appsecret,token} = require('./pageage/config');//获取测试号基本信息和自己写的token

app.get('/',(req,res)=>{
    /*
    {
        signature: '2a0d2d9aa7ea9621923f8b1b4570cae401b2d80f',
        echostr: '383011767707205355',
        timestamp: '1653277385',
        nonce: '241450439'
    }
    */
    // console.log(req.query);
    const {signature,echostr,timestamp,nonce} = req.query
    const sha1Str = sha1([timestamp,nonce,token].sort().join(''));//sha1加密的三个数据排序后的字符串后的结果就是signature签名的数据，如果不是就不能成功发送
    if(sha1Str === signature){
        res.send(echostr);
    }else {
        res.send('error');
    }
});

//自动回复羽发送的post
const {AutoOne,AutoTwo} = require('./pageage/AutoReply')
app.post('/',async (req,res)=>{
    let data1 = await getUserSendPostAsync(req);
    // console.log(data);
    // res.send(data);
    let data2 = await xmlToJsFunc(data1);
    // console.log(data);
    const {ToUserName,
        FromUserName,
        CreateTime,
        MsgType,
        Content,
        MsgId} = data2;
        console.log(Content[0]);
        // console.log(await AutoOne(data2));
        // let data3 = await AutoOne(data2);//回复发送的信息
        let data3 = await AutoTwo(data2,"在吗？","不在");
        // console.log(data3);
    // res.send(Content[0]);
    // console.log(data3);
    res.send(data3);
    res.end('')
    /* let data = "";
    req.on('data',chunk=> data += chunk);
    req.on('end',()=>{console.log(data)})
    res.send(data); */
});

//获取AccessToken
const {getAccessToken} = require('./pageage/getAccessToken')
app.get('/accesstoken',async (req,res)=>{
    res.send(await getAccessToken());
})

//自定义菜单
const {create_meun,delete_meun} = require('./pageage/CustomMeun');
app.get('/create_meun',async (req,res)=>{
    res.send(await create_meun());
})
app.get('/delete_meun',async (req,res)=>{
    res.send(await delete_meun());
})

//网页授权
//http%3A%2F%2Fchentianyu.free.idcfengye.com%2Fwww
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx029c9b44dcf8867f&redirect_uri=http%3A%2F%2Fchentianyu.free.idcfengye.com%2Fwww&response_type=code&scope=snsapi_base&state=123#wechat_redirect

//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx029c9b44dcf8867f&redirect_uri=http%3A%2F%2Fchentianyu.free.idcfengye.com%2Fwww&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
const {getOauthAccessToken} = require('./pageage/getAccessToken');
const {getOauthUserInfo} = require('./pageage/getOauthAll');
/* app.get('/www',async(req,res)=>{
    const CODE = req.query.code;
    const state = req.query.state;
    console.log(CODE);
    // let ac = await getOauthAccessToken(CODE);//获取到了我们的access_token
    // console.log(ac);
    let userinfo = await getOauthUserInfo(CODE);
    console.log(userinfo);
    res.send(`<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>你的个人信息</title>
        <style>
            .one{
                justify-content: center;
                align-items: center;
            }
            .one img{
                border-radius: 50%;
            }
        </style>
    </head>
    <body>
        <div class="one">
            <img src="${userinfo.headimgurl}" alt="" />
            <p>你的名字:${userinfo.nickname}</p>
            <p>你的openid:${userinfo.openid}</p>
        </div>
    </body>
    </html>`);
}) */

app.get('/hello',(req,res)=>{
    res.send("Hello");
})

//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx029c9b44dcf8867f&redirect_uri=http%3A%2F%2Fchentianyu.free.idcfengye.com%2Fwww&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
const {saveOauthUserInfo} = require('./pageage/savePages');
const fs = require('fs');
app.get('/www',async(req,res)=>{
    const CODE = req.query.code;
    const state = req.query.state;
    
    // fs.stat(`./jsonPage/${}.json`)

    let userinfo = await saveOauthUserInfo(CODE);
    // let userinfo = await getOauthUserInfo(CODE);
    console.log(userinfo);
    res.send(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>你的个人信息</title>
        <style>
            .one{
                justify-content: center;
                align-items: center;
            }
            .one img{
                border-radius: 50%;
            }
        </style>
    </head>
    <body>
        <div class="one">
            <img src="${userinfo.yuanUserInfo.headimgurl}" alt="" />
            <p>你的名字:${userinfo.yuanUserInfo.nickname}</p>
            <p>你的openid:${userinfo.yuanUserInfo.openid}</p>
        </div>
    </body>
    </html>
    `);
});

app.listen(port,()=>console.log(`${port}端口已监听`));

